package com.ruix.app.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.JsonObject;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.mapper.OrderMentorMapper;
import com.ruix.app.model.WebParcel;
import com.ruix.app.network.ApiConstant;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.service.UpdateAppService;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.ui.main.MainActivity;
import com.ruix.app.ui.stratum.setting.ClassMenberActivity;
import com.ruix.app.util.LogUitl;
import com.ruix.app.util.ThreadManager;
import com.ruix.app.util.WxpayOrderUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/5/4.
 */

public class CommonWebActivity extends BaseActivity{


    public static Intent newIntent(Context context, WebParcel webParcel) {
        Intent intent = new Intent(context, CommonWebActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("WebParcel", webParcel);
        intent.putExtras(bundle);
        return intent;
    }

    private WebView webView;
    private WebSettings webSettings;
    private WebParcel webParcel;
    private String cid;

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_comm_web;

    }

    @Override
    protected void initView() {
        webView =  (WebView)findViewById(R.id.web_view);
    }

    @Override
    protected void initLocalData() {
        Intent intent = getIntent();
        if (intent != null) {
            webParcel = (WebParcel) intent.getSerializableExtra("WebParcel");
        }
        if (webParcel != null) {
            if (!TextUtils.isEmpty(webParcel.getTitle())) {
                setTitle(webParcel.getTitle());
            }
            String url = webParcel.getUrl();
            if (url != null) {
                if (url.startsWith(RuiXConstant.WX_TEACHE_FREAND_CIRECLE_SHARE)) {
                    if (webParcel.isClassDetail()){
                        url += "&source=android&is_show_bottombar=0";
                    } else {
                        url += "&source=android&is_show_bottombar=1";
                        registerReceivers();//支付
                    }
                }

                String lastUA = webView.getSettings().getUserAgentString();
                webView.loadUrl(url);
            }
        }
    }

    private void addUserAgent(){
        String ua = " App/Android RuiX/"+ RuiApplication.appVersionCode;
        String lastUA = webView.getSettings().getUserAgentString();
        webView.getSettings().setUserAgentString(lastUA +ua);
//        App/Android RuiX/{VersionCode}
    }

    @Override
    protected void initListener() {
        webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setBlockNetworkImage(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.setWebViewClient(new WebViewClient(){

//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                return false;
//            }
//
//
//
//            public void onLoadResource(WebView view, String url) {
//            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!webView.getSettings().getLoadsImagesAutomatically()) {
                    webView.getSettings().setLoadsImagesAutomatically(true);
                }
                webSettings.setBlockNetworkImage(false);
            }

        });
        webView.setWebChromeClient(new WebChromeClient(){


            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (TextUtils.isEmpty(webParcel.getTitle())) {
                    setTitle(title);
                }
            }

        });
        //.joinButtonClicked

        webView.addJavascriptInterface(new AppBridgeJS(),"AppBridge");
        addUserAgent();
    }

    class AppBridgeJS{

        @JavascriptInterface
        public void  joinButtonClicked(String abc){
            //{"encrypt_id":"dErkx8WOwFYzVCkPJGEXqQ=="}
            if (abc != null){
                try {
                    JSONObject object = new JSONObject(abc);
                    String id =  object.optString("encrypt_id","");
                    if (!TextUtils.isEmpty(id)){
                        loadOrderClassInfo(id);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    public void loadOrderClassInfo(String enid){
        RequestFactory.wxOrderMentor(enid, new OrderMentorMapper(), new RXObserver<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String value) {
                //付费 //免费
                cid = value;
                if (!TextUtils.isEmpty(value)){
                    payClass(value);
                }
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    public void payClass(String id){
        RequestFactory.payClass(id, null, new RXObserver<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject value) {
                //TODO
                if (value != null){
                   JSONObject data =  value.optJSONObject("data");
                    if (data != null){
                       String charge =  data.optString("charge","");
                        if (!TextUtils.isEmpty(charge)){
                            try {
                                JSONObject changeObj = new JSONObject(charge);
                                String appid = changeObj.optString("appid", "");
                                String partnerid = changeObj.optString("partnerid", "");
                                String prepayid = changeObj.optString("prepayid", "");
                                String packagestr = changeObj.optString("package", "");
                                String noncestr = changeObj.optString("noncestr", "");
                                String timestamp = changeObj.optString("timestamp", "");
                                String sign = changeObj.optString("sign", "");
                                if (WxpayOrderUtil.isInstalled()){
                                    WxpayOrderUtil.paySeller(appid,partnerid,prepayid,packagestr,noncestr,timestamp,sign);
                                } else {
                                    showErrorTip("请安装微信");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else {
                            int success = data.optInt("success",1);
                            if (success == 1){
                                redirectClassDetail();
                            }
                        }
                    }
                }

//                Intent intent = new Intent(CommonWebActivity.this,MainActivity.class);
//                startActivity(intent);
            }

            @Override
            public void onError(Throwable e) {
                resolveException(e);
            }

            @Override
            public void onComplete() {

            }
        });

    }


    private void registerReceivers(){
        if (myReceiver == null) {
            myReceiver = new MyBroadcastReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_WX_PAY_RESULT);
        registerReceiver(myReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
    }

    private void unregisterReceivers(){
        if (myReceiver != null){
            unregisterReceiver(myReceiver);
        }
    }

    private BroadcastReceiver myReceiver;

     class MyBroadcastReceiver extends BroadcastReceiver{

         @Override
         public void onReceive(Context context, Intent intent) {
             if (RuiXConstant.NOTICE_WX_PAY_RESULT.equals(intent.getAction())){
                 String result =  intent.getStringExtra("WXPAY_RESULT");
                 if (!TextUtils.isEmpty(result)){
                     try {
                         JSONObject object = new JSONObject(result);
                         if (object != null){
                             String resultStatus = object.optString("resultStatus","");
                             if ("0".equals(resultStatus)){
                                 //支付成功
                                 delayRedirect();
                             }
                         }
                     } catch (JSONException e) {
                         e.printStackTrace();
                     }
                 }
             }
         }
     }


    private void delayRedirect(){
        ThreadManager.getScheduledThreadPool().schedule(new Runnable() {
            @Override
            public void run() {
                redirectClassDetail();
            }
        }, 2000, TimeUnit.MILLISECONDS);
    }

    private void redirectClassDetail(){
        Intent intent = new Intent(CommonWebActivity.this,MainActivity.class);
        intent.putExtra("ACTION","CLASS_DETAIL");
        intent.putExtra("CID",cid);
        startActivity(intent);
        finish();
    }


}
